package org.ccay.excel.exporter.service.impl.internal;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.ccay.async.task.ExportTaskVO;
import org.ccay.async.task.service.IExportTaskService;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.IUserPrincipal;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.util.StringUtil;
import org.ccay.excel.exception.ExcelExportConstants;
import org.ccay.excel.exporter.ExportTaskRequest;
import org.ccay.excel.util.impl.ExcelUtil;
//import org.ccay.mail.MailVO;
//import org.ccay.mail.service.IMailService;
import org.ccay.message.PushMessageVO;
import org.ccay.message.service.IPushMessageService;

/**
 * 导入监视器，针对导入的各种异常或者完成情况进行监视，并更新数据库状态
 * @author chaowangbang
 * @since 2012-5-26
 */
public class ExportMonitor {
	
	/** 日志记录器 **/
	private ILogger log = CcayLoggerFactory.getLogger(ExportMonitor.class);
	/**
	 * 导出任务服务
	 */
	private IExportTaskService exportTaskService;
	
	/**
	 * 导出请求
	 */
	private ExportTaskRequest exportRequest ;
	
	/** 邮件服务 **/
//	private IMailService defaultMailService;
	
	
	/** 消息推送服务 **/
	private IPushMessageService pushMessageService;
	
	private static final String BASE_PATH = "Ccay.Excel.SendMail";
	
	/** 
	 * 开始导出时触发，更新任务状态
	 */
	public void begin()throws ApplicationException {
		// 记录任务开始运行的时间
		long beginTime = System.currentTimeMillis();
		// 更新任务信息
		ExportTaskVO exportTaskVO = new ExportTaskVO();
		exportTaskVO.setTaskId(Integer.valueOf(exportRequest.getTaskId()));
		exportTaskVO.setExportFlag(ExcelExportConstants.STATUS_EXPORTING);
		exportTaskVO.setRunStartTime(new Date(beginTime));
		exportTaskService.updateExportTask(exportTaskVO);
	}
	
	/** 
	 * 正常结束时触发
	 */
	public void end()throws ApplicationException {
				
		// 记录任务结束运行的时间
		long endTime = System.currentTimeMillis();
		// 更新任务信息
				ExportTaskVO exportTaskVO = buildTask(ExcelExportConstants.STATUS_EXPORTED);
		//设置文件名
		exportTaskVO.setTmpName(exportRequest.getFileName());
		exportTaskVO.setFileName(exportRequest.getFileStore());
		exportTaskVO.setFileSize(exportRequest.getFileSize());
		exportTaskVO.setTotalCount(exportRequest.getTotalCount());
		exportTaskVO.setRunEndTime(new Date(endTime));
		exportTaskService.updateExportTask(exportTaskVO);	
		sendMessage();
	}
	
	
	/** 
	 * 失败时触发
	 * @param ex
	 */
	public void fail(Throwable ex) throws ApplicationException{
	 // 记录任务结束运行的时间
		long endTime = System.currentTimeMillis();
		// 更新任务信息
		ExportTaskVO exportTaskVO = buildTask(ExcelExportConstants.STATUS_EXCEPTION);
		exportTaskVO.setRunEndTime(new Date(endTime));
		exportTaskVO.setTotalCount(0);
		exportTaskVO.setFileName(ExcelUtil.buildErrorMsg4Security(ex));
		exportTaskService.updateExportTask(exportTaskVO);		
		sendMessage();
	}
	/**
	 * 执行消息
	 * @throws ApplicationException
	 * Created：2012-12-6
	 * @author chaowangbang
	 */
	private void sendMessage() throws ApplicationException{
		//如果任务id为空 那么直接取消
		if(StringUtil.isNullOrEmpty(exportRequest.getTaskId())){
			log.debug("taskId is null.");
			return ;
		}
		ExportTaskVO task = exportTaskService.findExportTaskById(Integer.valueOf(exportRequest.getTaskId()));
		//获取当前用户
		IUserPrincipal user =  RequestContext.getCurrent().getUser();
		try{
			//推送消息
			pushMessage(user, task);
		}finally{
			//发送邮件
			sendMail(user, task);
		}
	}
	/**
	 * 
	 * @throws ApplicationException
	 * Created：2012-7-20
	 * @author chaowangbang
	 */
	private void sendMail(IUserPrincipal user, ExportTaskVO task) throws ApplicationException{
//		//数据字典配置的发送邮件标识
//		if(!"1".equals(registryService.findValueByPath(BASE_PATH + ".ExportSendMail", false, "1"))){
//			log.debug("Registry [Ccay.Excel.SendMail.ExportSendMail] ] !=1. Mail will not be sent.");
//			return ;
//		}
//		MailVO mail = new MailVO();
//		mail.setTo(new String[]{user.getEmail()});
//		mail.setTemplateName("excel_mail_template");
//		Map<String,Serializable> bindItems = new HashMap<String,Serializable>();
//		//任务类型
//		bindItems.put("taskType", "ExcelExport");
//		//用户全名
//		bindItems.put("taskOwner", user.getUserCN());
//		bindItems.put("task", task);
//		TemplateUtil.putAppRoot(bindItems);
//		mail.setBindItems(bindItems);
//		//任务
//		defaultMailService.sendMail(mail);
	}

	
	/** 
	 * @param user
	 * @param task
	 */
	private void pushMessage(IUserPrincipal user, ExportTaskVO message) {
		//消息推送 x00228022
		PushMessageVO pushMessage=new PushMessageVO();
		pushMessage.setMessageType("ExcelExport");
		Map<String,Serializable> bindItems = new HashMap<String,Serializable>();
		//任务类型
		bindItems.put("messageType", "ExcelExport");
		//用户全名
		bindItems.put("messageOwner", user.getDisplayName());
		bindItems.put("message", message);
		pushMessage.setBindItems(bindItems);
		pushMessageService.sendAsyncMessage(pushMessage);
	}
	
//	public void setDefaultMailService(IMailService defaultMailService) {
//		this.defaultMailService = defaultMailService;
//	}
	
	public void setPushMessageService(IPushMessageService pushMessageService) {
		this.pushMessageService = pushMessageService;
	}


	/**
	 * 构建一个任务
	 * @param status
	 * @return
	 * @throws ApplicationException
	 */
	private ExportTaskVO buildTask(String status) throws ApplicationException {
		ExportTaskVO exportTaskVO = new ExportTaskVO();
		exportTaskVO.setTaskId(Integer.valueOf(exportRequest.getTaskId()));
		exportTaskVO.setExportFlag(status);
		return exportTaskVO;
	}
	/**
	 * @return the exportTaskService
	 */
	public IExportTaskService getExportTaskService() {
		return exportTaskService;
	}

	/**
	 * @param exportTaskService the exportTaskService to set
	 */
	public void setExportTaskService(IExportTaskService exportTaskService) {
		this.exportTaskService = exportTaskService;
	}

	/**
	 * @return the exportRequest
	 */
	public ExportTaskRequest getExportRequest() {
		return exportRequest;
	}

	/**
	 * @param exportRequest the exportRequest to set
	 */
	public void setExportRequest(ExportTaskRequest exportRequest) {
		this.exportRequest = exportRequest;
	}
}
